package org.example.springboot.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.springboot.component.SseEmitterServer;
import org.example.springboot.entity.*;
import org.example.springboot.service.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Slf4j
@Component
public class accETHandler {

    @Resource
    private IrrigationUnitService irrigationUnitService;

    @Resource
    private ColDeviceDataComputesynchService colDeviceDataComputesynchService;

    @Resource
    private ETService etService;

    @Resource
    private FmcDataService fmcDataService;

    @Resource
    private FmcMetricsService fmcMetricsService;

    @Resource
    private SseEmitterServer sseEmitterServer;

    @Scheduled(fixedRate = 900000)
    public void reportCurrentTime(){
        // 记录任务执行日志
        log.info("cumulativeETHandler-ET累计任务已执行");

        // 获取 fmcMetricsList 数据
        List<FmcMetrics> fmcMetricsList = fmcMetricsService.list();
        log.info("fmcMetricsList数据个数：{}", fmcMetricsList.size());

        // 创建线程池
        int threadPoolSize = 10;  // 线程池大小可以根据实际需求调整
        ExecutorService executorService = Executors.newFixedThreadPool(threadPoolSize);

        // 创建一个任务列表
        List<Callable<Void>> tasks = new ArrayList<>();

        for (FmcMetrics fmcMetrics : fmcMetricsList) {
            tasks.add(() -> {
                try {
                    IrrigationUnit irrigationUnit = irrigationUnitService.getOne(new QueryWrapper<IrrigationUnit>().eq("control_device", fmcMetrics.getDid()));
                    if (irrigationUnit != null) {
                        ET et = etService.getOne(new QueryWrapper<ET>().eq("irrigation_unit_uuid", irrigationUnit.getUuid()));
                        if (et == null) {
                            throw new RuntimeException("ET信息不存在");
                        }
                        String equipmentId = et.getEquipmentId();
                        // 如果设备信息不为空
                        LocalTime now = LocalTime.now();
                        LocalTime time = LocalTime.of(19, 0);
                        LocalTime time1 = LocalTime.of(7, 0);
                        if (StringUtils.isNotBlank(equipmentId) && !now.isAfter(time) && !now.isBefore(time1)) {
                            // 根据设备ID和格式化后的时间查询最新的数据计算记录
                            FmcData fmcData = fmcDataService.getOne(new QueryWrapper<FmcData>()
                                    .eq("did", equipmentId)
                                    .orderByDesc("ctime").last("limit 1"));
                            if (fmcData != null) {
                                log.info("FmcData表ID：{}", fmcData.getId());
                                ColDeviceDataComputesynch deviceDataComputesynch = null;
                                for(int i = 0; i < 10; i++){
                                    Thread.sleep(1000);  // 模拟处理时间
                                    deviceDataComputesynch = colDeviceDataComputesynchService.getOne(new QueryWrapper<ColDeviceDataComputesynch>().eq("data_id", fmcData.getId()));
                                    if(null != deviceDataComputesynch){
                                        log.info("ColDeviceDataComputesynch对象：{}", deviceDataComputesynch);
                                        // 如果查询到了数据计算记录
                                        log.info("ett0值：{}", deviceDataComputesynch.getEtt0());
                                        log.info("fmcMetrics表的et值：{}", fmcMetrics.getEt() == null ? 0 : fmcMetrics.getEt());
                                        // 更新蒸散量指标记录
                                        float et1 = deviceDataComputesynch.getEtt0() + (fmcMetrics.getEt() == null ? 0 : fmcMetrics.getEt());
                                        log.info("计算后ET值：{}", et1);
                                        fmcMetricsService.update(new UpdateWrapper<FmcMetrics>().set("et", et1).eq("id", fmcMetrics.getId()));
                                        // 推送更新通知
                                        sseEmitterServer.broadcast("Refresh");
                                        break;
                                    }
                                    log.info("FmcData表ID：{},执行次数：{}", fmcData.getId(),i);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("处理FmcMetrics失败，fmcMetricsId: {}", fmcMetrics.getId(), e);
                }
                return null;  // Callable需要返回一个结果，这里返回null表示无返回结果
            });
        }

        // 提交所有任务并等待执行完成
        try {
            // 执行任务并等待所有任务完成
            List<Future<Void>> futures = executorService.invokeAll(tasks);
            // 等待所有任务完成
            for (Future<Void> future : futures) {
                try {
                    future.get();  // 获取每个任务的执行结果，如果任务抛出异常，会在这里抛出
                } catch (ExecutionException e) {
                    log.error("任务执行失败", e);
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("任务提交或执行中被中断", e);
        } finally {
            // 关闭线程池
            executorService.shutdown();
        }
    }

}